package com.shuqi.database.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

import android.content.Context;
import android.text.TextUtils;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.database.dao.OrmBaseDao;
import com.shuqi.database.model.TxtDownload;

/**
 * 
 * @author yaozhen
 * 
 */
public class TxtDownloadDao extends OrmBaseDao {

    private static TxtDownloadDao mInstance;

    private RuntimeExceptionDao<TxtDownload, Integer> mDao = ShuqiDatabaseHelper.getHelper(
            ShuqiApplication.getContext()).getRuntimeExceptionDao(TxtDownload.class);

    private TxtDownloadDao(Context context) {

    }

    public static synchronized TxtDownloadDao getInstance() {
        if (mInstance == null) {
            mInstance = new TxtDownloadDao(ShuqiApplication.getContext());
        }
        return mInstance;
    }

    /**
     * 查询所有的下载txt信息，与当前用户无关
     * 
     * @return
     */
    public List<TxtDownload> getTxtDownloadList() {
        QueryBuilder<TxtDownload, Integer> queryBuilder = mDao.queryBuilder();
        queryBuilder.orderBy("create_time", false);
        try {
            return queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 保存离线下载书籍的信息
     * 
     * @param info
     * @return
     */
    public void saveTxtDownloadInfo(final TxtDownload info) {
        if (info == null || TextUtils.isEmpty(info.getBookId())
                || TextUtils.isEmpty(info.getDownloadUrl())) {
            return;
        }
        info.setCreateTime(System.currentTimeMillis());
        Callable<Void> callble = new Callable<Void>() {

            @Override
            public Void call() throws Exception {
                DeleteBuilder<TxtDownload, Integer> deleteBuilder = mDao.deleteBuilder();
                deleteBuilder.where().eq("book_id", info.getBookId()).and()
                        .eq("download_url", info.getDownloadUrl());
                deleteBuilder.delete();
                mDao.create(info);
                return null;
            }

        };
        try {
            openTransactionManager(ShuqiDatabaseHelper.getHelper(ShuqiApplication.getContext()),
                    callble);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新离线下载书籍的 下载状态，总文件大小，已下载大小
     * 
     * @param info
     * @return
     */
    public int updateTxtDownloadInfo(TxtDownload info) {
        if (info == null || TextUtils.isEmpty(info.getBookId())) {
            return -1;
        }
        UpdateBuilder<TxtDownload, Integer> updateBuilder = mDao.updateBuilder();
        try {
            updateBuilder.where().eq("book_id", info.getBookId()).and()
                    .eq("download_url", info.getDownloadUrl());
            updateBuilder.updateColumnValue("download_status", info.getDownloadStatus());
            updateBuilder.updateColumnValue("file_totla_size", info.getFileTotalSize());
            updateBuilder.updateColumnValue("file_download_size", info.getFileDownloadSize());
            return updateBuilder.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 删除单本离线下载书籍
     * 
     * @param bookId
     * @return
     */
    public int deleteTxtDownloadInfo(String bookId, String downloadUrl) {
        if (TextUtils.isEmpty(bookId)) {
            return -1;
        }
        DeleteBuilder<TxtDownload, Integer> deleteBuilder = mDao.deleteBuilder();
        try {
            deleteBuilder.where().eq("book_id", bookId).and().eq("download_url", downloadUrl);
            return deleteBuilder.delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 根据id获取离线下载书籍的信息
     * 
     * @param bid
     * @return
     */
    public TxtDownload getTxtDownload(String bookId, String downloadUrl) {
        if (TextUtils.isEmpty(bookId)) {
            return null;
        }
        QueryBuilder<TxtDownload, Integer> queryBuilder = mDao.queryBuilder();
        try {
            queryBuilder.where().eq("book_id", bookId).and().eq("download_url", downloadUrl);
            List<TxtDownload> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                return list.get(0);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
